import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import '../settings-responsive.css';
import { Settings, Languages, Map, Bell, Download, User, Shield, Moon, Sun, Check, AlertCircle, Search, X, ArrowRight, RefreshCw } from 'lucide-react';
import useSettingsService from '../services/settings-service';
import useTheme from '../hooks/useTheme';

// 设置项类型定义
interface SettingItem {
  name: string;
  type: 'toggle' | 'select' | 'link' | 'value';
  settingName?: keyof typeof settings;
  description: string;
  icon?: React.ReactNode;
  options?: { value: string; label: string }[];
  value?: string;
  link?: string;
  category?: string;
}

// 设置区块类型定义
interface SettingsSection {
  id: string;
  title: string;
  icon: React.ElementType;
  items: SettingItem[];
  category: string;
}

const SettingsPage: React.FC = () => {
  const { settings, updateSettings, isLoading, error, getCurrentTheme, refreshSettings } = useSettingsService();
  const [activeSection, setActiveSection] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterCategory, setFilterCategory] = useState<string | null>(null);
  const { theme, toggleTheme } = useTheme();

  // 切换设置值
  const toggleSetting = (settingName: keyof typeof settings) => {
    updateSettings({
      [settingName]: !settings[settingName]
    });
  };

  // 选择设置值
  const selectSetting = (settingName: keyof typeof settings, value: any) => {
    updateSettings({
      [settingName]: value
    });
  };

  // 语言选项
  const languageOptions = [
    { value: 'zh', label: '简体中文' },
    { value: 'en', label: 'English' },
    { value: 'ja', label: '日本語' },
    { value: 'ko', label: '한국어' },
    { value: 'fr', label: 'Français' },
    { value: 'es', label: 'Español' }
  ];

  // 地图类型选项
  const mapTypeOptions = [
    { value: 'standard', label: '标准地图' },
    { value: 'satellite', label: '卫星地图' },
    { value: 'terrain', label: '地形地图' },
    { value: 'hybrid', label: '混合地图' }
  ];

  // 自动下载选项
  const autoDownloadOptions = [
    { value: 'wifi', label: '仅WiFi' },
    { value: 'cellular', label: 'WiFi和移动数据' },
    { value: 'never', label: '永不自动下载' },
    { value: 'smart', label: '智能下载' }
  ];

  // 主题选项
  const themeOptions = [
    { value: 'light', label: '浅色模式' },
    { value: 'dark', label: '深色模式' },
    { value: 'system', label: '跟随系统' }
  ];

  // 设置分类
  const categories = [
    { id: 'interface', name: '界面设置' },
    { id: 'content', name: '内容设置' },
    { id: 'privacy', name: '隐私与安全' },
    { id: 'account', name: '账户管理' },
    { id: 'notifications', name: '通知设置' }
  ];

  // 设置区块 (按分类和逻辑顺序排列)
  const settingsSections: SettingsSection[] = [
    // 界面设置
    {
      id: 'appearance',
      title: '外观设置',
      icon: Settings,
      category: 'interface',
      items: [
        {
          name: '主题模式',
          type: 'select',
          settingName: 'theme',
          description: '选择应用主题',
          options: themeOptions,
          icon: theme === 'dark' ? <Moon className="h-4 w-4" /> : theme === 'light' ? <Sun className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />
        },
        {
          name: '界面语言',
          type: 'select',
          settingName: 'language',
          description: '设置应用界面显示语言',
          options: languageOptions
        },
        {
          name: '字体大小',
          type: 'select',
          settingName: 'fontSize',
          description: '调整界面文字大小',
          options: [
            { value: 'small', label: '小' },
            { value: 'medium', label: '中' },
            { value: 'large', label: '大' }
          ]
        },
        {
          name: '高对比度模式',
          type: 'toggle',
          settingName: 'highContrast',
          description: '提高界面对比度，增强可读性'
        }
      ]
    },

    // 内容设置
    {
      id: 'language',
      title: '语言设置',
      icon: Languages,
      category: 'content',
      items: [
        {
          name: '翻译偏好',
          type: 'select',
          settingName: 'preferredTranslationLanguage',
          description: '设置默认翻译语言',
          options: languageOptions
        },
        {
          name: '自动检测语言',
          type: 'toggle',
          settingName: 'autoDetectLanguage',
          description: '自动检测输入文本语言'
        },
        {
          name: '翻译历史',
          type: 'toggle',
          settingName: 'saveTranslationHistory',
          description: '保存您的翻译历史记录'
        }
      ]
    },
    {
      id: 'map',
      title: '地图设置',
      icon: Map,
      category: 'content',
      items: [
        {
          name: '地图类型',
          type: 'select',
          settingName: 'mapType',
          description: '选择默认地图显示类型',
          options: mapTypeOptions
        },
        {
          name: '定位服务',
          type: 'toggle',
          settingName: 'locationEnabled',
          description: '允许应用获取您的位置信息'
        },
        {
          name: '地图缩放级别',
          type: 'select',
          settingName: 'mapZoomLevel',
          description: '设置默认地图缩放级别',
          options: [
            { value: '1', label: '最小' },
            { value: '5', label: '小' },
            { value: '10', label: '中' },
            { value: '15', label: '大' },
            { value: '20', label: '最大' }
          ]
        }
      ]
    },
    {
      id: 'offline',
      title: '离线内容',
      icon: Download,
      category: 'content',
      items: [
        {
          name: '自动下载',
          type: 'select',
          settingName: 'autoDownload',
          description: '设置内容下载条件',
          options: autoDownloadOptions
        },
        {
          name: '存储管理',
          type: 'link',
          value: '170MB/1GB',
          description: '管理离线内容存储空间',
          link: '/offline-content'
        },
        {
          name: '离线翻译',
          type: 'toggle',
          settingName: 'offlineTranslation',
          description: '启用离线翻译功能（需要下载语言包）'
        }
      ]
    },

    // 隐私与安全
    {
      id: 'privacy',
      title: '隐私与安全',
      icon: Shield,
      category: 'privacy',
      items: [
        {
          name: '数据隐私',
          type: 'link',
          value: '查看政策',
          description: '了解我们如何保护您的数据',
          link: '/privacy-policy'
        },
        {
          name: '使用统计',
          type: 'toggle',
          settingName: 'analyticsEnabled',
          description: '帮助改进应用体验'
        },
        {
          name: '地理位置',
          type: 'toggle',
          settingName: 'locationServices',
          description: '允许应用访问您的地理位置信息'
        },
        {
          name: '安全锁',
          type: 'toggle',
          settingName: 'appLock',
          description: '使用密码或生物识别保护应用'
        }
      ]
    },
    {
      id: 'account',
      title: '账户设置',
      icon: User,
      category: 'account',
      items: [
        {
          name: '个人资料',
          type: 'link',
          value: '编辑',
          description: '管理您的个人信息',
          link: '/profile'
        },
        {
          name: '同步设置',
          type: 'toggle',
          settingName: 'syncSettings',
          description: '在设备间同步您的设置'
        },
        {
          name: '备份数据',
          type: 'link',
          value: '立即备份',
          description: '手动备份您的应用数据',
          link: '/backup'
        }
      ]
    },

    // 通知设置
    {
      id: 'notifications',
      title: '通知设置',
      icon: Bell,
      category: 'notifications',
      items: [
        {
          name: '推送通知',
          type: 'toggle',
          settingName: 'notificationEnabled',
          description: '接收重要消息和更新通知'
        },
        {
          name: '声音提醒',
          type: 'toggle',
          settingName: 'soundEnabled',
          description: '播放通知声音'
        },
        {
          name: '振动提醒',
          type: 'toggle',
          settingName: 'vibrationEnabled',
          description: '收到通知时振动'
        },
        {
          name: '通知预览',
          type: 'toggle',
          settingName: 'notificationPreview',
          description: '在锁定屏幕上显示通知内容预览'
        }
      ]
    }
  ];

  // 过滤设置区块
  const filteredSections = settingsSections
    .filter(section => !filterCategory || section.category === filterCategory)
    .map(section => ({
      ...section,
      items: section.items.filter(item => 
        item.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
        item.description.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }))
    .filter(section => section.items.length > 0);

  return (
    <div className={`min-h-screen py-8 page-container ${theme === 'dark' ? 'bg-gray-900' : 'bg-gray-50'}`}>
      <div className="content-centered max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="mb-8">
          <h1 className={`settings-title text-responsive font-bold mb-4 text-balance ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>设置</h1>
          <p className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-600'}`}>个性化您的旅行助手体验</p>

          {/* 搜索框 */}
          <div className={`settings-search relative mt-6 rounded-md shadow-sm ${theme === 'dark' ? 'bg-gray-800' : 'bg-white'}`}>
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <Search className={`h-5 w-5 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`} />
            </div>
            <input
              type="text"
              className={`block w-full pl-10 pr-10 py-3 rounded-md ${theme === 'dark' ? 'bg-gray-800 text-white border-gray-700' : 'bg-white text-gray-900 border-gray-300'} border focus:ring-blue-500 focus:border-blue-500 sm:text-sm`}
              placeholder="搜索设置..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            {searchQuery && (
              <button
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                onClick={() => setSearchQuery('')}
              >
                <X className={`h-5 w-5 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`} />
              </button>
            )}
          </div>

          {/* 分类筛选 */}
          <div className="settings-tabs-container mt-6 overflow-x-auto pb-2">
            <div className="flex space-x-2 min-w-max">
              <button
                key="all"
                className={`settings-tab px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${filterCategory === null ? 'bg-blue-600 text-white' : theme === 'dark' ? 'bg-gray-800 text-gray-300 hover:bg-gray-700' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
                onClick={() => setFilterCategory(null)}
              >
                全部
              </button>
              {categories.map(category => (
                <button
                  key={category.id}
                  className={`settings-tab px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${filterCategory === category.id ? 'bg-blue-600 text-white' : theme === 'dark' ? 'bg-gray-800 text-gray-300 hover:bg-gray-700' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
                  onClick={() => setFilterCategory(category.id)}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="space-y-6 w-full max-w-3xl mx-auto">
          {/* 加载状态和错误提示 */}
          {isLoading && (
            <div className="bg-white rounded-lg shadow-sm p-6 text-center">
              <p className="text-gray-600">加载设置中...</p>
            </div>
          )}

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex">
                <AlertCircle className="h-5 w-5 text-red-400 mr-2" />
                <div>
                  <h3 className="text-sm font-medium text-red-800">
                    加载失败
                  </h3>
                  <p className="text-sm text-red-700 mt-1">
                    {error}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* 设置区块 */}
          <AnimatePresence>
            {!isLoading && filteredSections.map((section) => {
              const Icon = section.icon;
              return (
                <motion.div 
                  key={section.id} 
                  className={`rounded-lg shadow-sm transition-all hover:shadow-md overflow-hidden w-full ${theme === 'dark' ? 'bg-gray-800' : 'bg-white'}`}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  transition={{ duration: 0.3 }}
                >
                  <div
                    className={`p-6 border-b cursor-pointer ${theme === 'dark' ? 'border-gray-700' : 'border-gray-200'}`}
                    onClick={() => setActiveSection(activeSection === section.id ? null : section.id)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center">
                        <Icon className={`h-5 w-5 mr-3 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`} />
                        <h2 className={`text-responsive font-medium text-balance ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>
                          {section.title}
                        </h2>
                      </div>
                      <motion.div
                        animate={{ rotate: activeSection === section.id ? 90 : 0 }}
                        transition={{ duration: 0.3 }}
                      >
                        <ArrowRight className={`h-5 w-5 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`} />
                      </motion.div>
                    </div>
                  </div>

                  <AnimatePresence>
                    {activeSection === section.id && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3 }}
                        className={`divide-y ${theme === 'dark' ? 'divide-gray-700' : 'divide-gray-200'}`}
                      >
                        {section.items.map((item) => (
                          <div key={item.name} className={`p-6 hover:bg-opacity-50 transition-colors duration-200 ${theme === 'dark' ? 'hover:bg-gray-700' : 'hover:bg-gray-50'}`}>
                            <div className="flex items-center justify-between flex-wrap gap-3">
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center">
                                  {item.icon && <span className={`mr-2 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`}>{item.icon}</span>}
                                  <h3 className={`text-sm font-medium truncate ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>
                                    {item.name}
                                  </h3>
                                </div>
                                <p className={`text-sm mt-1 truncate ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`}>
                                  {item.description}
                                </p>
                              </div>
                              <div className="ml-4 whitespace-nowrap">
                                {item.type === 'toggle' ? (
                                  <button
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      if (item.settingName) {
                                        toggleSetting(item.settingName);
                                      }
                                    }}
                                    className={`relative inline-flex items-center h-6 rounded-full w-11 transition-colors duration-200 ease-in-out ${item.settingName && settings[item.settingName] ? 'bg-blue-600' : theme === 'dark' ? 'bg-gray-700' : 'bg-gray-200'}`}
                                  >
                                    <motion.span
                                      className={`absolute left-0.5 bg-white border border-gray-300 h-5 w-5 rounded-full`}
                                      animate={{ x: item.settingName && settings[item.settingName] ? 20 : 0 }}
                                      transition={{ type: 'spring', stiffness: 500, damping: 30 }}
                                    />
                                  </button>
                                ) : item.type === 'select' ? (
                                  <select
                                    value={item.settingName ? settings[item.settingName] : ''}
                                    onChange={(e) => {
                                      if (item.settingName) {
                                        selectSetting(item.settingName, e.target.value);
                                      }
                                    }}
                                    className={`shadow-sm focus:ring-blue-500 focus:border-blue-500 block text-sm rounded-md p-1 ${theme === 'dark' ? 'bg-gray-700 text-white border-gray-600' : 'bg-white border-gray-300'}`}
                                  >
                                    {item.options?.map(option => (
                                      <option key={option.value} value={option.value}>
                                        {option.label}
                                      </option>
                                    ))}
                                  </select>
                                ) : item.type === 'link' ? (
                                  <motion.a
                                    href={item.link}
                                    className="text-sm text-blue-500 hover:text-blue-600 flex items-center"
                                    whileHover={{ x: 5 }}
                                    transition={{ type: 'spring', stiffness: 500, damping: 30 }}
                                  >
                                    {item.value} <ArrowRight className="h-3 w-3 ml-1" />
                                  </motion.a>
                                ) : (
                                  <span className={`text-sm px-3 py-1 rounded-full ${theme === 'dark' ? 'bg-gray-700 text-gray-300' : 'bg-gray-100 text-gray-600'}`}>
                                    {item.value}
                                  </span>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              );
            })}
          </AnimatePresence>

          {/* 应用信息 */}
          <div className={`mt-8 rounded-lg shadow-sm p-6 ${theme === 'dark' ? 'bg-gray-800' : 'bg-white'}`}>
            <h2 className={`text-lg font-medium mb-4 ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>应用信息</h2>
            <p className={`text-sm ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`}>版本: 1.0.0</p>
            <p className={`text-sm mt-1 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-500'}`}>© 2023 旅行助手应用</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingsPage;